package org.cable.account.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.cable.account.model.TrafficDO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author hsj
 * @since 2023-10-25
 */
@Mapper
public interface TrafficMapper extends BaseMapper<TrafficDO> {

	/**
	 * 删除过期流量包
	 * @return
	 */
	@Delete("delete from traffic where expired_date <= now()")
	boolean deleteExpireTraffic();

	/**
	 * 查找可⽤的短链流量包(未过期),包括免费流量包
	 * @param accountNo
	 * @return
	 */
	@Select("select * from traffic where account_no = #{accountNo} where plugin_type ='SHORT_LINK' and (expired_date >= now() or out_trade_no = 'free_init' )")
	List<TrafficDO> selectAvailableTraffics(@Param("accountNo") Long accountNo);

	/**
	 * 给某个流量包增加使⽤次数
	 * @param accountNo
	 * @param trafficId
	 * @param usedTimes
	 * @return
	 */
	@Update("update traffic set day_used = day_used + #{usedTimes} where id =#{trafficId} and account_no =#{accountNo} and (day_limit - day_used) >= #{usedTimes}")
	int addDayUsedTimes(@Param("accountNo") Long accountNo, @Param("trafficId") Long trafficId, @Param("usedTimes") Integer usedTimes) ;

	/**
	 *  恢复流量包使⽤当天次数
	 * @param accountNo
	 * @param trafficId
	 * @param useTimes
	 * @return
	 */
	@Update("update traffic set  day_used = day_used - #{usedTimes} where id =#{trafficId} and account_no =#{accountNo} and (day_used - #{usedTimes}) >= 0 limit 1")
	int releaseUsedTimes(@Param("accountNo") long accountNo, @Param("trafficId") Long trafficId, @Param("usedTimes") Integer useTimes);

	/**
	 * 批量更新流量包使用次数为0
	 * @param accountNo
	 * @param unUpdatedTrafficIds
	 * @return
	 */
	int batchUpdateUsedTimes(@Param("accountNo") Long accountNo, @Param("unUpdatedTrafficIds") List<Long> unUpdatedTrafficIds);

}
